import Taro, {Component} from '@tarojs/taro'
import {View, Button, Image, Text} from '@tarojs/components'
import {AtAvatar} from 'taro-ui'
// AtModal
import login from '../../utils/login'
import {connect} from '@tarojs/redux'
import * as actions from '../../actions/wx'
import mobile from '../../assets/img/mine/mobile.png'
// import shoucang from '../../assets/img/mine/shoucang.png'
import version from '../../assets/img/mine/version.png'
import about from '../../assets/img/mine/about.png'
import feedback from '../../assets/img/mine/feedback.png'
import kefu from '../../assets/img/mine/kefu.png'
import wx from '../../assets/img/mine/wx.png'
import kuaidi from '../../assets/img/mine/kuaidi.png'
import download from '../../utils/download'
import {isWeapp} from '../../utils/platform'


import './index.scss'

const wxImg = "https://qiniuqianshop.fortunemy.top/public-qian-wx.jpeg"

@connect(state => state.wx, {...actions})
class Mine extends Component {


  state = {
    showBtn: true, // 授权按钮是否显示 默认为显示
    isOpened: false
  }

  static options = {
    addGlobalClass: true,
    styleIsolation: 'shared'
  }

  config = {
    navigationBarTitleText: '',
    navigationStyle: "custom"
  }

  componentWillMount() {
    console.log('mine')
    // 获取用户当前授权状态
    //  this.getOauthStatus()
  }

  componentDidMount() {
    // if (!openId) {
    //   Taro.navigateTo({
    //     url: `/pages/auth/index`
    //   })
    // }

  }

  copy() {
    Taro.setClipboardData({
      data: 'qq95476020',
      success: (res) => {
        Taro.showToast({
          title: '复制微信号成功',
        });
      }
    })
  }

  componentDidShow() {
    this.init()
  }

  componentDidHide() {
  }

  componentCatchError() {
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.pullDown === true && this.props.pullDown != nextProps.pullDown && this.props.tabIndex == 1) {
      //切换了menuItem
      this.init()
    }
  }

  async init() {
    const token = Taro.getStorageSync('token')
    if (!token) {
      this.setState({
        showBtn: true
      })
      this.props.onFinishPullDown()
    } else {
      this.setState({
        showBtn: false
      })
      await this.props.dispatchWxUser()
      this.props.onFinishPullDown()
    }
  }

  async chaKuaidi() {
    Taro.navigateTo({
      url: '/pages/delivery/index'
    })
  }

  render() {
    const {showBtn, isOpened} = this.state
    const {userInfo} = this.props
    const token = Taro.getStorageSync('token')
    return (
      <View className="mine-page">
        <View className="mine_bg">
          <View className="mine_bg_clear" onClick={this.logout.bind(this)}>清空缓存</View>
          {/* <View> */}
          {
            showBtn && <AtAvatar circle className="mine_bg_avator"></AtAvatar>
          }
          {
            showBtn &&
            <View>
              <Button className='mine_bg_btn'
                      openType='getUserInfo'
                      onGetUserInfo={this.login.bind(this)}>
                点击授权登录
              </Button>
              {/* <Button open-type="getPhoneNumber" onGetphonenumber={this.getPhoneNumber.bind(this)} className="mine_bg_content_desc">
                        <Text className="at-icon at-icon-iphone mine_bg_content_desc_icon"></Text>绑定手机号码
                  </Button> */}
            </View>
          }
          {
            (!showBtn && userInfo) ?
              <AtAvatar circle image={userInfo.avatarUrl} className="mine_bg_avator"></AtAvatar> : null
          }
          {
            (!showBtn && userInfo) ?
              <View className="mine_bg_content">
                <Text className="mine_bg_content_title">
                  {userInfo.nickName}
                </Text>
                {
                  userInfo && userInfo.phoneNumber &&
                  <View className="mine_bg_content_desc">{userInfo.phoneNumber}</View>
                }
                {/* <Button open-type="getPhoneNumber" onGetphonenumber={this.getPhoneNumber.bind(this)} className="mine_bg_content_desc">
                        <Text className="at-icon at-icon-iphone mine_bg_content_desc_icon"></Text>绑定手机号码
                    </Button> */}
              </View>
              : null
          }
          {/* </View> */}
        </View>
        <View className="mine_list mine_list1">
          {/* <View className="mine_list_item mine_list_item_extra" onClick={this.seeShoucang.bind(this)}>
                <view className="mine_list_item_button">
                    <Image src={shoucang} className="mine_list_item_icon"></Image>
                   我的收藏
                </view>
                <View className='at-icon at-icon-chevron-right'></View>
                <View className="mine_list_item_line"/>
            </View> */}
          <View className="mine_list_item mine_list_item_extra">
            <Button open-type='contact' session-from='' className="mine_list_item_button" show-message-card={false}>
              <Image src={kefu} className="mine_list_item_icon" webp></Image>
              我的客服
            </Button>
            <View className='at-icon at-icon-chevron-right'></View>
            <View className="mine_list_item_line"/>
          </View>
          <View className="mine_list_item mine_list_item_extra" onClick={this.chaKuaidi.bind(this)}>
            <view className="mine_list_item_button">
              <Image src={kuaidi} className="mine_list_item_icon" webp></Image>
              快递查询
            </view>
            <View className='at-icon at-icon-chevron-right'></View>
          </View>
          <View className="mine_list_item mine_list_item_extra">
            {
              token && !userInfo.phoneNumber &&
              <Button open-type="getPhoneNumber" onGetphonenumber={this.getPhoneNumber.bind(this)}
                      className="mine_list_item_button">
                <Image src={mobile} className="mine_list_item_icon" webp></Image>
                绑定手机
              </Button>
            }
            {
              token && userInfo.phoneNumber &&
              <Button onClick={this.hasPhoneNumber.bind(this)} className="mine_list_item_button">
                <Image src={mobile} className="mine_list_item_icon" webp></Image>
                绑定手机
              </Button>
            }
            {
              !token &&
              <Button onClick={this.shouldLogin.bind(this)} className="mine_list_item_button">
                <Image src={mobile} className="mine_list_item_icon" webp></Image>
                绑定手机
              </Button>
            }
            <View className='at-icon at-icon-chevron-right'></View>
            <View className="mine_list_item_line"/>
          </View>
          <View className="mine_list_item mine_list_item_extra" onClick={this.copy.bind(this)}>
            <view className="mine_list_item_button">
              <Image src={wx} className="mine_list_item_icon" webp></Image>
              管理员微信
            </view>
            <View className='at-icon at-icon-chevron-right'></View>
            <View className="mine_list_item_line"/>
          </View>
          <View className="mine_list_item mine_list_item_extra" onClick={this.jumpAbout.bind(this)}>
            <view className="mine_list_item_button">
              <Image src={about} className="mine_list_item_icon" webp></Image>
              关于我们
            </view>
            <View className='at-icon at-icon-chevron-right'></View>
          </View>
        </View>
        <View className="mine_list">
          <View className="mine_list_item mine_list_item_extra">
            <Button open-type="feedback" className="mine_list_item_button">
              <Image src={feedback} className="mine_list_item_icon" webp></Image>
              意见反馈
            </Button>
            <View className='at-icon at-icon-chevron-right'></View>
            <View className="mine_list_item_line"/>
          </View>
          <View className="mine_list_item mine_list_item_extra">
            <View className="mine_list_item_button">
              <Image src={version} className="mine_list_item_icon" webp></Image>
              当前版本
            </View>
            <Text>
              {isWeapp() ? Taro.getAccountInfoSync().miniProgram.version : '1.0.0'}
            </Text>
          </View>
        </View>
        {/* <AtCurtain
        closeBtnPosition="bottom"
        isOpened={this.state.isOpened}
        onClose={this.onClose.bind(this)}
      >
        <Image
          style='width:100%;height:300px'
          src="https://qiniuqianshop.fortunemy.top/public-qian-wx.jpeg"
        />
      </AtCurtain> */}
        {/* <AtModal isOpened={isOpened} onClose={this.closeModal.bind(this)} className="mine_wx">

        <AtModalContent className="ccc">
            <View className="mine_wx_body" onLongPress={this.saveImage.bind(this)}>
              <Image
                className="mine_wx_image"
                src={wxImg}
                mode="widthFix"
              />
              <View className="mine_wx_desc">
                <View>长按保存到本地</View>
              </View>
            </View>

        </AtModalContent>
      </AtModal> */}

      </View>
    )
  }

  closeModal() {
    this.setState({
      isOpened: false
    })
  }

  hasPhoneNumber() {
    Taro.showToast({
      title: '已绑定！',
      icon: 'none'
    })
  }

  shouldLogin() {
    Taro.showToast({
      title: '请先登录！',
      icon: 'none'
    })
  }

  getPhoneNumber(e) {
    const token = Taro.getStorageSync('token')
    if (!token) {
      Taro.showToast({
        title: '请先登录！',
        icon: 'none'
      })
      return;
    }
    const {encryptedData, iv} = e.detail
    console.log('e', e)
    console.log(e.detail.errMsg)
    console.log(e.detail.iv)
    console.log(e.detail.encryptedData)
    if (encryptedData && iv) {
      this.props.dispatchWxBindPhone(iv, encryptedData).then(res => {

      })
    } else {
      Taro.showToast({
        title: '获取手机号失败'
      })
    }


  }

  onClose() {
    this.setState({
      isOpened: false
    })
  }

  wxModal() {
    this.setState({
      isOpened: true
    })
  }

  seeShoucang() {
    const token = Taro.getStorageSync('token')
    if (!token) {
      Taro.navigateTo({
        url: `/pages/auth/index?redirect=/pages/like/index`
      })
    } else {
      Taro.navigateTo({
        url: `/pages/like/index`
      })
    }
  }

  jumpAbout() {
    Taro.navigateTo({
      url: `/pages/about/index`
    })
  }

  async login() {
    const result = await login()
    const {userInfo, code} = result
    if (userInfo) {
      this.props.dispatchWxLogin(code, userInfo).then(token => {
        this.setState({
          showBtn: false
        })
        this.props.dispatchWxUser()
      })
    }

// nickName: "啊尼啊塞呦"
// gender: 1
// language: "zh_CN"
// city: "太原"
// province: "山西"
// country: "中国"
// avatarUrl:''
  }


  logout() {
    const token = Taro.getStorageSync('token')
    if (token) {
      this.props.dispatchWxLogout().then(() => {
        this.clear()
      })
    } else {
      this.clear()
    }
  }

  clear() {
    Taro.clearStorage().then(res => {
      Taro.showToast({
        title: '清除成功',
        icon: 'success',
        duration: 2000
      })
      this.setState({
        showBtn: true,
        userInfo: null
      })
    }).catch(errMsg => {
      Taro.showToast({
        title: '清除失败',
        icon: 'close',
        duration: 2000
      })
    })
  }

  saveImage() {
    download(wxImg)
  }

}

export default Mine
